package com.zmzncs.lmtc.module.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmzncs.lmtc.module.shop.dao.GoodsFileDao;
import com.zmzncs.lmtc.module.shop.pojo.shop_goods.*;
import com.zmzncs.lmtc.module.shop.dao.GoodsDao;
import com.zmzncs.lmtc.module.shop.pojo.shop_goods_file.GoodsFile;
import com.zmzncs.lmtc.module.shop.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 商户-商品 服务实现类
 * </p>
 *
 * @author 高博文
 * @since 2021-05-20
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {

    @Autowired
    GoodsDao goodsDao;
    @Autowired
    GoodsFileDao goodsFileDao;

    @Transactional
    @Override
    public void add(GoodsAddForm form) {

        Goods goods = new Goods();
        BeanUtils.copyProperties(form,goods);
        goods.setStatus(1);
        goods.setIsDeleted(0);
        goodsDao.insert(goods);

        List<String> imageList = form.getImageList();
        for (String url : imageList) {
            GoodsFile goodsFile = new GoodsFile();
            goodsFile.setGoodsId(goods.getId());
            goodsFile.setFileUrl(url);
            goodsFile.setIsDeleted(0);
            goodsFileDao.insert(goodsFile);
        }

    }

    @Override
    public IPage<GoodsDTO> getGoodsPage(GoodsSelectForm form) {
        Page<Object> page = new Page<>(form.getCurrentPage(), form.getPageSize());
        return goodsDao.getGoodsPage(page,form);
    }

    @Override
    public GoodsDTO getGoodsById(Long goodsId) {
        Goods goods = goodsDao.selectById(goodsId);
        GoodsDTO goodsDTO = new GoodsDTO();
        BeanUtils.copyProperties(goods,goodsDTO);

        List<String> imageList = goodsFileDao.getFileByGoodsId(goodsId);
        goodsDTO.setImageList(imageList);

        return goodsDTO;
    }

    @Transactional
    @Override
    public void updateGoods(GoodsUpdateForm form) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(form,goods);
        goodsDao.updateById(goods);

        goodsFileDao.deleteByShopId(form.getId());

        List<String> imageList = form.getImageList();
        for (String url : imageList) {
            GoodsFile goodsFile = new GoodsFile();
            goodsFile.setGoodsId(goods.getId());
            goodsFile.setFileUrl(url);
            goodsFile.setIsDeleted(0);
            goodsFileDao.insert(goodsFile);
        }
    }

    @Override
    public List<GoodsDTO> getGoodsByShopId(Long shopId) {
        return goodsDao.getGoodsByShopId(shopId);
    }
}
